package main

import (
	"geekbang-go-homework/week05/window"
	"log"
	"math/rand"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup
	// 1s的滑动窗口
	p := window.NewRollingPolicy(time.Millisecond*100, 10)
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 10; j++ {
				t := time.Now()
				request()
				p.Add(float64(time.Since(t)))
			}
		}()
	}
	wg.Wait()
	stat := window.NewStatistical(p)
	log.Default().Printf("请求数：%v", stat.Count())
	log.Default().Printf("平均延迟：%v", time.Duration(stat.Avg()))
}

func request() {
	time.Sleep(time.Duration(rand.Int63n(int64(time.Millisecond * 200))))
}
